package com.infoland.afanmall.base.util;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.base.entity.RefreshResponse;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.vondear.rxtools.view.RxToast;


/**
 * 用户相关工具类
 */
public class UserKit {
    /**
     *
     */
    public static String SpaceName = "AfanAppUser";

    public boolean checkLogin() {
        return false;
    }


    public static void setUserCacheYes(String acesToken, String refTocken) {
        UserKit.putAccessToken(acesToken);
        UserKit.putRefreshToken(refTocken);
        UserKit.putIsLogin(true);
    }

    public static void setUserCacheNo(String acesToken, String refTocken) {
        UserKit.putAccessToken(acesToken);
        UserKit.putRefreshToken(refTocken);
        UserKit.putIsLogin(false);
    }

    public static void setUserCacheNo() {
        UserKit.putAccessToken("");
        UserKit.putRefreshToken("");
        UserKit.putIsLogin(false);
    }


    /***获取是否第一次使用App**/
    public static boolean isFirstUse() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getBoolean("first_login", true);
    }

    public static void putFirstUse(boolean b) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putBoolean("first_login", b);
        editor.apply();
    }

    /***获取是否为更新状态**/
    public static boolean isUpdateApp() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getBoolean("update_app", true);
    }

    public static void putUpdateApp(boolean b) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putBoolean("update_app", b);
        editor.apply();
    }

    /***获取UserInFo**/
    public static String getUserInFoEntity() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getString("user_in_fo_entity", "");
    }

    public static void putUserInFoEntity(String user_info) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putString("user_in_fo_entity", user_info);
        editor.apply();
    }

    /***获取是否登陆**/
    public static boolean isLogin() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getBoolean("is_login", false);
    }

    public static void putIsLogin(boolean isLogin) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putBoolean("is_login", isLogin);
        editor.apply();
    }

    /***获取是否第一次登陆**/
    public static boolean isFirstLogin() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getBoolean("first_login", false);
    }

    public static void putFirstLogin(boolean firstLogin) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putBoolean("first_login", firstLogin);
        editor.apply();
    }

    /***获取 AccessToken（用来访问请求）**/
    public static String getAccessToken() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getString("access_token", "");
    }

    public static void putAccessToken(String access) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putString("access_token", access);
        editor.apply();
    }

    /***获取RefreshToken（用来刷新AccessToken）**/
    public static String getRefreshToken() {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        return sp.getString("refresh_tocken", "");
    }

    public static void putRefreshToken(String refresh) {
        SharedPreferences sp = CacheKit.APP_CONTEXT.getSharedPreferences(SpaceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit().putString("refresh_tocken", refresh);
        editor.apply();
    }

    /**
     * 微信登录
     */
    public static void loginWeinXin() {
        LogKit.E(" WXEntryActivity.wxapi.isWXAppInstalled()  ", "  " + WXEntryActivity.wxapi.isWXAppInstalled());
        if (!WXEntryActivity.wxapi.isWXAppInstalled()) {
            RxToast.showToast("您还未安装微信客户端");
            return;
        }
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = CONST.WEIXIN_SCOPE;
        req.state = CONST.WEIXIN_STATE;
        WXEntryActivity.wxapi.sendReq(req);
    }

    /***
     * 发送验证码
     * @param para 参数
     * @param waiCengLL 外层layout
     * @param txtLL  textView
     * @param wait_time 等待时长
     * @param interval  间隔
     * @param hint   提示文字
     */
    public static void sendValidateCode(JSONObject para, LinearLayout waiCengLL,
                                        TextView txtLL, long wait_time, long interval, String hint, Activity activity) {
        String url = CONST.HTTP + CONST.SEND_VALIDATE_CODE;
        LogKit.E("url   ", "  " + url);
        LogKit.E("para   ", "  " + para.toJSONString());
        new OkHttpKit().send(
                response200 -> {
                    JSONObject jsonObject1 = JSONObject.parseObject(response200);
                    if (jsonObject1.getBoolean("success")) {
                        LogKit.E("验证码  response ", "  " + response200);
                    } else {
                        LogKit.E("  发送失败 ", "  " + jsonObject1.getString("message"));
                        ToolsKit.daoJishi(waiCengLL, txtLL, wait_time, interval, hint);
                        ToastUtils.showShort("验证码发送频繁，请稍后再试");
                    }
                    LogKit.E("response200 ---->   ", "  " + response200);
                },
                error401 -> {
                    LogKit.E("success401 ---->   ", "  " + error401);
                },
                error -> {
                    ToolsKit.daoJishi(waiCengLL, txtLL, wait_time, interval, hint);
                }
        ).post(CONST.SEND_VALIDATE_CODE, para, activity);
        ToastUtils.showShort("验证码发送成功");
        ToolsKit.daoJishi(waiCengLL, txtLL, wait_time, interval, hint);
    }

    /*** 刷新Tocken**/
    public static void startRefresh(Activity activity) {
        String url = CONST.HTTP + CONST.REFERENCE_TOKEN + "?" + "refresh_token=" + UserKit.getRefreshToken();
        LogKit.E("当前 refresh_token--->  ", "  " + UserKit.getRefreshToken());
        LogKit.E("当前 access_token--->  ", "  " + UserKit.getAccessToken());
        new OkHttpKit().send(
                response200 -> {
                    LogKit.E(" 刷新Token---> onResponse ", "  " + response200);
                    RefreshResponse refreshResponse = JSONObject.parseObject(response200, RefreshResponse.class);
                    if (refreshResponse.isSuccess()) {
                        UserKit.setUserCacheYes(refreshResponse.getObject().getAccess_token(), refreshResponse.getObject().getRefresh_token());
                    } else {
                        UserKit.setUserCacheNo();
                    }
                },
                error -> {
                    LogKit.E(" 刷新Token---> onSuccess ", "  " + error);
                    UserKit.setUserCacheNo();
                }
        ).get(url, new JSONObject(), activity);
    }

}
